from PySide6.QtWidgets import QWidget, QVBoxLayout, QTreeWidget, QTreeWidgetItem, QSizePolicy
from PySide6.QtCore import Qt, QSize
from PySide6.QtGui import QIcon
import os

class FileManagerTab(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ssh_thread = None
        self.setup_ui()
        
    def setup_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 8, 0, 0)
        layout.setSpacing(0)
        
        # 创建树形控件
        self.tree = QTreeWidget()
        self.tree.setObjectName("file_tree_view")
        self.tree.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
        
        # 设置列标题
        self.tree.setColumnCount(1)
        self.tree.setHeaderLabels(['名称'])
        
        # 设置列宽
        self.tree.setColumnWidth(0, 300)
        
        # 设置树形控件的样式和行为
        self.tree.setIndentation(20)  # 设置缩进
        self.tree.setHeaderHidden(True)  # 隐藏表头
        self.tree.setRootIsDecorated(True)  # 显示展开/折叠图标
        self.tree.setIconSize(QSize(16, 16))  # 设置图标大小
        
        # 设置其他控件属性
        self.tree.setAlternatingRowColors(True)
        self.tree.setUniformRowHeights(True)
        self.tree.setAnimated(True)
        self.tree.setSortingEnabled(True)
        
        layout.addWidget(self.tree)
        
    def set_ssh_thread(self, ssh_thread):
        """设置SSH线程并连接信号"""
        self.ssh_thread = ssh_thread
        if self.ssh_thread:
            self.ssh_thread.directory_loaded.connect(self.update_directory_view)
            self.ssh_thread.error.connect(self.handle_error)
            # 监听SFTP连接状态
            self.ssh_thread.sftp_connected.connect(self._on_sftp_connected)
            
    def _on_sftp_connected(self, connected):
        """处理SFTP连接状态变化"""
        if connected:
            # SFTP连接成功后再执行目录列表操作
            self.ssh_thread.list_directory('/')
        else:
            # SFTP连接失败，清空目录视图
            self.tree.clear()
            
    def update_directory_view(self, items):
        """更新目录视图"""
        self.tree.clear()
        
        for item in items:
            tree_item = QTreeWidgetItem(self.tree)
            tree_item.setText(0, item['name'])
            
            # 设置文件夹图标
            if item['is_dir']:
                tree_item.setIcon(0, QIcon(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static', 'icons', 'folder-1.png')))
            
            # 存储完整路径
            tree_item.setData(0, Qt.ItemDataRole.UserRole, item['path'])
            
    def handle_error(self, error_message):
        """处理错误信息"""
        # TODO: 添加错误处理逻辑，可以显示错误对话框或更新状态栏
        pass